import {
  Component, Output, Input, EventEmitter, HostListener, AfterViewInit, OnDestroy,
  SimpleChanges, OnChanges
} from '@angular/core';
import { ControlValueAccessor, NgControl } from '@angular/forms';
@Component({
  selector: 'datetime',
  template: `
          <input id="{{idDatePicker}}" type="text" class="form-control"
                         [attr.readonly]="readonly"
                         [attr.autocomplete]="autocomplete"
                         [attr.required]="required"
                         [attr.placeholder]="datepickerOptions.placeholder || '请选择日期'"
                         [(ngModel)]="dateModel"
                         (blur)="onTouched();"
                         (change)="onDateChange();"
                         (keyup)="checkEmptyValue($event)"/>
    `,
  styles: ['']
})
export class NKDatetime implements ControlValueAccessor, AfterViewInit, OnDestroy, OnChanges {
  @Output() dateChange: EventEmitter<string> = new EventEmitter<string>();
  @Input('datepicker') datepickerOptions: any = {};
  @Input('hasClearButton') hasClearButton = false;
  @Input() readonly: boolean = null;
  @Input() required: boolean = null;
  @Input() autocomplete: any = 'off';
  @Output() ondatechange = new EventEmitter<boolean>();
  date: string; // ngModel
  dateModel: string;
  // instances
  datepicker: any;
  idDatePicker: string = uniqueId('q-datepicker_');
  @HostListener('dateChange', ['$event'])
  onChange = (_: any) => {
  }
  onTouched = () => {
  }
  onDateChange() {
    this.ondatechange.emit();
  }
  constructor(public ngControl: NgControl) {
    ngControl.valueAccessor = this; // override valueAccessor
  }
  ngAfterViewInit() {
    this.init();
  }
  ngOnDestroy() {
    if (this.datepicker) {
      this.datepicker.datepicker('destroy');
    }
  }
  ngOnChanges(changes: SimpleChanges) {
    if (changes) {
      if (changes['datepickerOptions'] && this.datepicker) {
        this.datepicker.datepicker('destroy');
        if (changes['datepickerOptions'].currentValue) {
          this.datepicker = null;
          this.init();
        } else if (changes['datepickerOptions'].currentValue === false) {
          this.datepicker.remove();
        }
      }
    }
  }
  writeValue(value: any): void {
    this.date = value;
    setTimeout(() => {
      this.updateModel(this.date);
    }, 0);
  }
  registerOnChange(fn: (_: any) => void): void {
    this.onChange = fn;
  }
  registerOnTouched(fn: () => void): void {
    this.onTouched = fn;
  }
  checkEmptyValue(e: any) {
    const value = e.target.value;
    if (value === '' && (
      this.datepickerOptions === false || this.dateModel === ''
    )) {
      if (this.required) {
        if (value && value !== '') {
          $('#' + this.idDatePicker).addClass('ng-valid');
        } else {
          $('#' + this.idDatePicker).removeClass('ng-valid');
          $('#' + this.idDatePicker).addClass('ng-invalid');
        }
      }
      this.dateChange.emit(null);
    }
  }
  clearModels() {
    this.dateChange.emit(null);
    this.updateDatepicker(null);
  }
  showDatepicker() {
    this.datepicker.datepicker('show');
  }
  private init(): void {
    if (!this.datepicker && this.datepickerOptions !== false) {
      const options = $.extend({ enableOnReadonly: !this.readonly }, this.datepickerOptions);
      this.datepicker = (<any>$('#' + this.idDatePicker)).datepicker(options);
      const value = $('#' + this.idDatePicker).val();
      if (this.required) {
        if (value && value !== '') {
          $('#' + this.idDatePicker).addClass('ng-valid');
        } else {
          $('#' + this.idDatePicker).removeClass('ng-valid');
          $('#' + this.idDatePicker).addClass('ng-invalid');
        }
      }

      $('#' + this.idDatePicker).on('change', function () {
        if (this.required) {
          if (this.value && this.value !== '') {
            $(this).addClass('ng-valid');
          } else {
            $(this).removeClass('ng-valid');
            $(this).addClass('ng-invalid');
          }
        }
      });
      this.datepicker
        .on('changeDate', (e: any) => {
          //          const v = $('#' + this.idDatePicker).val();
          const v = e.format();
          this.date = v;
          this.dateChange.emit(v);
          if (this.required) {
            if (v && v !== '') {
              $('#' + this.idDatePicker).addClass('ng-valid');
            } else {
              $('#' + this.idDatePicker).removeClass('ng-valid');
              $('#' + this.idDatePicker).addClass('ng-invalid');
            }
          }
        });
    } else if (this.datepickerOptions === false) {
      (<any>$('#' + this.idDatePicker)).remove();
    }
    this.updateModel(this.date);
  }
  private updateModel(date: string): void {
    this.updateDatepicker(date);
  }
  private updateDatepicker(date?: any) {
    if (this.datepicker !== undefined) {
      this.datepicker.datepicker('update', date);
    }
  }

  // 初始化开始时间
  private setStartDate(value: string): void {
    this.datepicker.datepicker('setStartDate', value);
  }

}
let id = 0;
function uniqueId(prefix: string): string {
  return prefix + ++id;
}
